<?php
/**
 * Product.php $id 28 - 2009-10-09 13:51 joao.gsneto
 *
 * Model of Product
 *
 * JLoja Project
 * @package    models
 * @author     Joao Neto <joao_neto@ymail.com>
 * @version    0.2
 */
class Product extends BaseProduct
{

	/**
	 * Add a new product to the Database
	 * 
	 * @param array		$arr	The array of product Infos ( see example )
	 * @return Product
	 * @throws JLoja_Exception	If has ocorred a fatal error
	 */
	public function addProduct( $arr )
	{
		$p = $this;
		if( isset( $arr[ 'product' ][ 'id_product' ] ) ){
			$p = $this->getTable()->find( $arr[ 'product' ][ 'id_product' ] );
		}

		if( !$p ){
			$p = $this;
		}
		try {
			Doctrine_Manager::connection()->beginTransaction();

			$p->_persistCategories( $arr[ 'categories' ] );
			$p->_persistTags( $arr[ 'tag' ] );
			$p->_persistMetadata( $arr[ 'metadata' ] );
			$p->_persistDescription( $arr[ 'description' ] );

			$p->save();
			Doctrine_Manager::connection()->commit();
			
		} catch (Exception $exc) {
			echo $exc->getMessage();
			Doctrine_Manager::connection()->rollback();
		}

		return $p;
	}

	/**
	 * Add a created date to the instance
	 * @param Doctrine_Event $row
	 */
	public function preInsert( Doctrine_Event $row )
	{
		$row->getInvoker()->dt_product_created = JLoja_Model::getDate();
	}

	private function _persistCategories( $categories )
	{
		$this->unlink( 'Categories' );
		$this->link( 'Categories', $categories );
	}

	private function _persistDescription( $description )
	{
		$this->ProductDescription->Translation[ JLoja_Lang::getPostLang() ]->fromArray( $description );
	}

	private function _persistMetadata( $metadata )
	{
		$this->ProductMetadata->Translation[ JLoja_Lang::getPostLang() ]->fromArray( $metadata );
	}

	private function _persistTags( $toSaveTags )
	{
		$productTags = new ProductTag();
		$producTag->addTagsToProduct( $this, $toSaveTags );
	}
}